
  var parts = { 
      0 : 'head',
      1 : 'mouth',
      2 : 'eyes',
      3 : 'hair',
      4 : 'tribune',
      5 : 'body'
    }; 
  $(document).ready(function() {
      var style_id =  $("input[name='body_style']").val();
      
      $('.avatar-style').click(function () {
        style_id =  $(this).attr('id').substr(6);
        $('.avatar-style').removeClass('selected');
        $(this).addClass('selected');
        $('#default-avatar').hide();
        $('#custom-avatar').attr('class', 'avatar avatar-style-' + style_id);
        $('#custom-avatar').show();
        $('.avatar-parts-section').show();
        $("input[name='body_style']").val(style_id);
        refresh_avatar(style_id);
        reload_thumbnails(style_id);
        $('#to-part-2-link').show();
      });
      
      $.each(parts, function(key, value) { 
        $('.avatar-' + value + '-tmb').click(function () {
          $('#avatar-piece-' + value + " img").attr('src', "" + globals['base_url'] + "images/avatars/" + value + "/" + value + '_' + style_id + '_' + $(this).attr("rel") + ".png");
          $("input[name='" + value + "_img']").val($(this).attr("rel"));
          $("#avatar-"+value+"-items").hide();
        });
      });
      
      $('.avatar-back-tmb').click(function () {
        $('#avatar-piece-back img').attr('src', "" + globals['base_url'] + 'images/avatars/back/back_' + $(this).attr("rel") + ".png");
        $("input[name='back_img']").val($(this).attr("rel"));
        $("#avatar-back-items").hide();
      });
      
      $('#to-part-1-link').click(function () {
        $("#form-part-2").hide();
        $("#form-part-1").show();
      });
      
      $('#to-part-2-link').click(function () {
        $("#form-part-1").hide();
        $("#form-part-2").show();
      });
      
      var last_valid_selection = '';
      $("select[name='first_part_sentence']").change(function(event) {
        if ($(this).val().length > 1) {
          $(this).val(last_valid_selection);
        } else {
          last_valid_selection = $(this).val();
        }
      });
    
  });
  

function reload_thumbnails(style_id) {
  $.each(parts, function(key, value) { 
    for (var i=1; i<=$('.avatar-' + value + '-tmb').length; i++) {
      $('#avatar-' + value + '-tmb-' + i).attr('src', globals['base_url']+'images/avatars/' + value + '/' + value + '_' + style_id + '_' + i + '_tmb.png');
    }
  });
}

function refresh_avatar(style_id) {
  $.each(parts, function(key, value) {
      $('#avatar-piece-' + value + " img").attr('src', "" + globals['base_url'] + 'images/avatars/' + value + '/' + value + '_' + style_id + '_' + $('input[name="' + value + '_img"]').val() + ".png");
  });
}

function show_items(items_key) {
  $('.avatar-items').hide();
  $('#avatar-' + items_key + '-items').show();
}